<template>
  <div class="ai-customer-service">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
           <el-icon class="header-icon">
             <Setting />
           </el-icon>
          <div class="header-text">
            <h1>AI智能客服系统</h1>
            <p>基于讯飞AI的智能对话与数据查询系统</p>
          </div>
        </div>
        <div class="header-stats">
          <div class="stat-item">
            <span class="stat-number">{{ statistics.totalConversations }}</span>
            <span class="stat-label">总对话数</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ statistics.todayQueries }}</span>
            <span class="stat-label">今日查询</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ statistics.successRate }}%</span>
            <span class="stat-label">成功率</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要功能区域 -->
    <div class="main-content">
      <el-row :gutter="24">
        <!-- 左侧：AI对话区域 -->
        <el-col :xl="14" :lg="14" :md="24" :sm="24" :xs="24">
          <el-card class="chat-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <div class="header-left">
                  <el-icon class="chat-icon">
                    <ChatDotRound />
                  </el-icon>
                  <span class="card-title">AI智能对话</span>
                </div>
                <div class="header-actions">
                  <el-button size="small" @click="clearCurrentChat">
                    <el-icon><Delete /></el-icon>
                    清空对话
                  </el-button>
                  <el-button size="small" @click="exportChat">
                    <el-icon><Download /></el-icon>
                    导出记录
                  </el-button>
                </div>
              </div>
            </template>

            <!-- 聊天内容区域 -->
            <div class="chat-container">
              <div class="chat-messages" ref="chatMessages">
                <!-- 欢迎消息 -->
                <div v-if="currentMessages.length === 0" class="welcome-section">
                  <div class="welcome-avatar">
                    <el-icon><Setting /></el-icon>
                  </div>
                  <h3>欢迎使用AI智能客服</h3>
                  <p>我可以帮助您查询各种业务数据，也可以进行日常对话交流。</p>
                  
                  <!-- 快捷操作按钮 -->
                  <div class="quick-actions">
                    <h4>快捷查询</h4>
                    <div class="action-buttons">
                      <el-button 
                        v-for="action in quickActions" 
                        :key="action.label"
                        size="small"
                        @click="sendQuickQuery(action.query)"
                        :icon="action.icon"
                      >
                        {{ action.label }}
                      </el-button>
                    </div>
                  </div>

                  <!-- 示例问题 -->
                  <div class="example-questions">
                    <h4>示例问题</h4>
                    <div class="question-list">
                      <div 
                        v-for="example in exampleQuestions" 
                        :key="example"
                        class="example-item"
                        @click="sendQuickQuery(example)"
                      >
                        {{ example }}
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 消息列表 -->
                <div v-for="message in currentMessages" :key="message.id" class="message-wrapper">
                  <div 
                    class="message-item" 
                    :class="{
                      'user-message': message.role === 'user',
                      'ai-message': message.role === 'assistant'
                    }"
                  >
                    <div class="message-avatar">
                      <el-icon v-if="message.role === 'user'">
                        <User />
                      </el-icon>
                      <el-icon v-else>
                        <Setting />
                      </el-icon>
                    </div>
                    <div class="message-content">
                      <div class="message-text" v-html="formatMessageContent(message.content)"></div>
                      <div class="message-meta">
                        <span class="message-time">{{ formatTime(message.timestamp) }}</span>
                        <el-button 
                          v-if="message.role === 'assistant'"
                          type="text" 
                          size="small"
                          @click="copyMessage(message.content)"
                        >
                          <el-icon><CopyDocument /></el-icon>
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 正在输入指示器 -->
                <div v-if="isTyping" class="typing-indicator">
                  <div class="typing-avatar">
                    <el-icon><Setting /></el-icon>
                  </div>
                  <div class="typing-content">
                    <div class="typing-dots">
                      <span></span>
                      <span></span>
                      <span></span>
                    </div>
                    <span class="typing-text">AI正在思考中...</span>
                  </div>
                </div>
              </div>

              <!-- 输入区域 -->
              <div class="chat-input-section">
                <div class="input-container">
                  <el-input
                    v-model="currentInput"
                    type="textarea"
                    :rows="3"
                    resize="none"
                    placeholder="请输入您的问题，支持数据查询和日常对话..."
                    @keydown.ctrl.enter="sendMessage"
                    @keydown.enter.prevent="sendMessage"
                    class="message-input"
                  />
                  <div class="input-actions">
                    <el-button 
                      type="primary"
                      @click="sendMessage"
                      :loading="isTyping"
                      :disabled="!currentInput.trim()"
                    >
                      <el-icon><Promotion /></el-icon>
                      发送
                    </el-button>
                  </div>
                </div>
                <div class="input-tips">
                  <span>按 Ctrl+Enter 快速发送</span>
                  <span>支持查询工单、物料、客户等业务数据</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 右侧：功能面板 -->
        <el-col :xl="10" :lg="10" :md="24" :sm="24" :xs="24">
          <!-- 系统统计 -->
          <el-card class="stats-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <el-icon><DataAnalysis /></el-icon>
                <span class="card-title">系统统计</span>
                <el-button size="small" @click="refreshStats" :loading="loadingStats">
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </div>
            </template>
            <div class="stats-content" v-loading="loadingStats">
              <div class="stats-grid">
                <div class="stat-card">
                  <el-icon class="stat-icon"><Folder /></el-icon>
                  <div class="stat-info">
                    <span class="stat-value">{{ systemStats.workOrderCount || 0 }}</span>
                    <span class="stat-name">工单总数</span>
                  </div>
                </div>
                <div class="stat-card">
                  <el-icon class="stat-icon"><Box /></el-icon>
                  <div class="stat-info">
                    <span class="stat-value">{{ systemStats.materialCount || 0 }}</span>
                    <span class="stat-name">物料数量</span>
                  </div>
                </div>
                <div class="stat-card">
                  <el-icon class="stat-icon"><User /></el-icon>
                  <div class="stat-info">
                    <span class="stat-value">{{ systemStats.customerCount || 0 }}</span>
                    <span class="stat-name">客户数量</span>
                  </div>
                </div>
                <div class="stat-card">
                  <el-icon class="stat-icon"><OfficeBuilding /></el-icon>
                  <div class="stat-info">
                    <span class="stat-value">{{ systemStats.warehouseCount || 0 }}</span>
                    <span class="stat-name">仓库数量</span>
                  </div>
                </div>
              </div>
              <div class="stats-summary">
                <p>{{ systemStats.answer || '系统运行正常，数据统计已更新。' }}</p>
              </div>
            </div>
          </el-card>

          <!-- 对话历史 -->
          <el-card class="history-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <el-icon><Clock /></el-icon>
                <span class="card-title">对话历史</span>
                <el-button size="small" @click="showHistoryDialog = true">
                  <el-icon><View /></el-icon>
                  查看全部
                </el-button>
              </div>
            </template>
            <div class="history-content">
              <div v-if="conversationHistory.length === 0" class="empty-history">
                <el-icon><ChatDotRound /></el-icon>
                <p>暂无对话历史</p>
              </div>
              <div v-else class="history-list">
                <div 
                  v-for="conversation in conversationHistory.slice(0, 5)" 
                  :key="conversation.id"
                  class="history-item"
                  @click="loadConversation(conversation)"
                >
                  <div class="history-preview">
                    <span class="history-text">{{ conversation.lastMessage }}</span>
                    <span class="history-time">{{ formatTime(conversation.timestamp) }}</span>
                  </div>
                  <div class="history-meta">
                    <span class="message-count">{{ conversation.messageCount }}条消息</span>
                  </div>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 快捷工具 -->
          <el-card class="tools-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <el-icon><Tools /></el-icon>
                <span class="card-title">快捷工具</span>
              </div>
            </template>
            <div class="tools-content">
              <el-row :gutter="12">
                <el-col :span="12" v-for="tool in quickTools" :key="tool.name">
                  <el-button 
                    class="tool-button"
                    @click="executeTool(tool)"
                    :loading="tool.loading"
                  >
                    <el-icon>
                      <component :is="tool.icon" />
                    </el-icon>
                    <span>{{ tool.name }}</span>
                  </el-button>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 对话历史详情对话框 -->
    <el-dialog
      v-model="showHistoryDialog"
      title="对话历史记录"
      width="800px"
      :before-close="handleHistoryDialogClose"
    >
      <div class="history-dialog-content">
        <div class="history-filters">
          <el-date-picker
            v-model="historyDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="filterHistory"
          />
          <el-input
            v-model="historySearchKeyword"
            placeholder="搜索对话内容"
            @input="filterHistory"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="history-table">
          <el-table
            :data="filteredHistory"
            height="400"
            @row-click="loadConversation"
          >
            <el-table-column prop="id" label="会话ID" width="100" />
            <el-table-column prop="lastMessage" label="最后消息" show-overflow-tooltip />
            <el-table-column prop="messageCount" label="消息数" width="80" />
            <el-table-column prop="timestamp" label="时间" width="150">
              <template #default="scope">
                {{ formatTime(scope.row.timestamp) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button size="small" @click.stop="loadConversation(scope.row)">
                  加载
                </el-button>
                <el-button size="small" type="danger" @click.stop="deleteConversation(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Setting, User, ChatDotRound, Delete, Download, CopyDocument,
  Promotion, DataAnalysis, Refresh, Clock, View, Tools,
  Folder, Box, OfficeBuilding, Search
} from '@element-plus/icons-vue'
import { APIs } from '@/Http/http'

// 接口定义
interface ChatMessage {
  id: string
  role: 'user' | 'assistant'
  content: string
  timestamp: Date
}

interface Conversation {
  id: string
  messages: ChatMessage[]
  lastMessage: string
  messageCount: number
  timestamp: Date
}

interface SystemStats {
  workOrderCount?: number
  materialCount?: number
  customerCount?: number
  warehouseCount?: number
  answer?: string
}

// 响应式数据
const currentInput = ref('')
const currentMessages = ref<ChatMessage[]>([])
const isTyping = ref(false)
const chatMessages = ref<HTMLElement>()
const showHistoryDialog = ref(false)
const loadingStats = ref(false)

// 统计数据
const statistics = reactive({
  totalConversations: 0,
  todayQueries: 0,
  successRate: 95
})

const systemStats = ref<SystemStats>({})

// 对话历史
const conversationHistory = ref<Conversation[]>([])
const historyDateRange = ref<[Date, Date] | null>(null)
const historySearchKeyword = ref('')

// 快捷操作配置
const quickActions = [
  { label: '工单查询', query: '查询工单信息', icon: 'Folder' },
  { label: '物料信息', query: '查询物料信息', icon: 'Box' },
  { label: '客户数据', query: '查询客户信息', icon: 'User' },
  { label: '仓库状态', query: '查询仓库信息', icon: 'OfficeBuilding' },
  { label: '系统统计', query: '获取系统统计信息', icon: 'DataAnalysis' }
]

const exampleQuestions = [
  '帮我查询编号为1的工单详情',
  '物料编码为1的物料信息是什么？',
  '客户名称包含"测试"的客户有哪些？',
  '当前系统的整体运行状态如何？',
  '今天的生产任务完成情况怎么样？'
]

const quickTools = ref([
  { name: '数据查询', icon: 'Search', loading: false },
  { name: '工单管理', icon: 'Folder', loading: false },
  { name: '物料管理', icon: 'Box', loading: false },
  { name: '客户管理', icon: 'User', loading: false }
])

// 计算属性
const filteredHistory = computed(() => {
  let filtered = conversationHistory.value

  // 日期筛选
  if (historyDateRange.value) {
    const [start, end] = historyDateRange.value
    filtered = filtered.filter(conv => 
      conv.timestamp >= start && conv.timestamp <= end
    )
  }

  // 关键词搜索
  if (historySearchKeyword.value) {
    const keyword = historySearchKeyword.value.toLowerCase()
    filtered = filtered.filter(conv => 
      conv.lastMessage.toLowerCase().includes(keyword)
    )
  }

  return filtered
})

// 发送消息
const sendMessage = async () => {
  if (!currentInput.value.trim() || isTyping.value) return

  const userMessage: ChatMessage = {
    id: Date.now().toString(),
    role: 'user',
    content: currentInput.value.trim(),
    timestamp: new Date()
  }

  currentMessages.value.push(userMessage)
  const messageContent = currentInput.value.trim()
  currentInput.value = ''
  
  await nextTick()
  scrollToBottom()

  isTyping.value = true

  try {
    // 判断消息类型并调用相应接口
    const response = await callAIService(messageContent)
    
    const aiMessage: ChatMessage = {
      id: (Date.now() + 1).toString(),
      role: 'assistant',
      content: String(response || '抱歉，AI暂时无法回复。'),
      timestamp: new Date()
    }

    currentMessages.value.push(aiMessage)
    
    // 更新统计
    statistics.todayQueries++
    
    // 保存对话历史
    saveConversationHistory()

  } catch (error) {
    console.error('AI服务错误:', error)
    const errorMessage: ChatMessage = {
      id: (Date.now() + 1).toString(),
      role: 'assistant',
      content: '抱歉，服务暂时不可用，请稍后再试。',
      timestamp: new Date()
    }
    currentMessages.value.push(errorMessage)
    ElMessage.error('AI服务暂时不可用')
  } finally {
    isTyping.value = false
    await nextTick()
    scrollToBottom()
  }
}

// 调用AI服务
const callAIService = async (message: string): Promise<string> => {
  console.log('🤖 开始调用AI服务:', message)
  
  // 检查是否是特定问题的固定回复
  const fixedResponse = checkFixedResponses(message)
  if (fixedResponse) {
    console.log('✅ 使用固定回复:', fixedResponse)
    return fixedResponse
  }
  
  // 判断是否需要数据查询
  const needsDataQuery = checkIfNeedsDataQuery(message)
  console.log('🔍 是否需要数据查询:', needsDataQuery)
  
  try {
    let response
    
    if (needsDataQuery) {
      console.log('📊 调用数据查询接口...')
      // 使用集成数据查询的接口
      response = await APIs.post('/api/AIAssistant/Chat', {
        message: message,
        sessionId: 'main-chat-' + Date.now(),
        history: currentMessages.value.slice(-10).map(m => ({
          role: m.role,
          content: m.content,
          timestamp: m.timestamp.toISOString()
        }))
      })
    } else {
      console.log('💬 调用简单聊天接口...')
      // 使用简单聊天接口
      response = await APIs.post('/api/AIAssistant/SimpleChat', message, {
        headers: {
          'Content-Type': 'application/json'
        },
        params: {
          sessionId: 'simple-chat-' + Date.now()
        }
      })
    }
    
    console.log('✅ AI服务响应:', response.data)
    
    // 检查响应数据格式
    if (response.data) {
      console.log('🔍 解析AI响应数据:', response.data)
      
      // 尝试多种可能的响应格式
      let result = null
      
      // 优先查找AI的文本回复，而不是数据结构
      // 首先检查是否有AI的直接文本回复
      if (response.data.answer && typeof response.data.answer === 'string') {
        result = response.data.answer
        console.log('✅ 找到AI文本回复 (answer):', result)
      } else if (response.data.message && typeof response.data.message === 'string') {
        result = response.data.message  
        console.log('✅ 找到AI文本回复 (message):', result)
      } else if (response.data.content && typeof response.data.content === 'string') {
        result = response.data.content
        console.log('✅ 找到AI文本回复 (content):', result)
      } else if (response.data.result && typeof response.data.result === 'string') {
        result = response.data.result
        console.log('✅ 找到AI文本回复 (result):', result)
      } else if (response.data.data && typeof response.data.data === 'string') {
        result = response.data.data
        console.log('✅ 找到AI文本回复 (data):', result)
      } else if (response.data.response) {
        // response字段特殊处理
        if (typeof response.data.response === 'string') {
          result = response.data.response
          console.log('✅ 找到AI文本回复 (response string):', result)
        } else if (typeof response.data.response === 'object') {
          // 检查response对象中是否有AI的文本回复
          const responseObj = response.data.response
          if (responseObj.answer && typeof responseObj.answer === 'string') {
            result = responseObj.answer
            console.log('✅ 找到AI文本回复 (response.answer):', result)
          } else if (responseObj.message && typeof responseObj.message === 'string') {
            result = responseObj.message
            console.log('✅ 找到AI文本回复 (response.message):', result)
          } else if (responseObj.content && typeof responseObj.content === 'string') {
            result = responseObj.content
            console.log('✅ 找到AI文本回复 (response.content):', result)
          } else {
            // 如果response对象中没有文本回复，可能是纯数据查询结果
            console.log('⚠️ response是数据对象，格式化为可读文本:', responseObj)
            result = formatObjectToText(responseObj)
          }
        }
      } else if (response.data.data && typeof response.data.data === 'object') {
        // 如果data是对象，格式化显示
        console.log('🔍 data是对象，格式化显示:', response.data.data)
        result = formatObjectToText(response.data.data)
      } else if (typeof response.data === 'string') {
        result = response.data
      } else {
        // 如果是对象，尝试找到文本内容
        console.warn('🔍 尝试从对象中提取文本:', response.data)
        
        // 检查对象的所有属性，找到可能的AI回复文本
        // 排除技术性字段，优先查找可能的AI回复
        const keys = Object.keys(response.data)
        const excludeKeys = ['sessionId', 'token', 'code', 'msg', 'dataCount', 'dataType', 'hasData', 'processingTime']
        
        for (const key of keys) {
          const value = response.data[key]
          if (typeof value === 'string' && value.trim().length > 0 && !excludeKeys.includes(key)) {
            // 检查是否像AI回复（包含中文且长度合理）
            if (value.length > 5 && /[\u4e00-\u9fa5]/.test(value)) {
              console.log(`✅ 找到可能的AI回复在字段 "${key}":`, value)
              result = value
              break
            }
          }
        }
        
        // 如果没有找到AI回复，再检查所有字符串字段
        if (!result) {
          for (const key of keys) {
            const value = response.data[key]
            if (typeof value === 'string' && value.trim().length > 0 && !excludeKeys.includes(key)) {
              console.log(`✅ 找到文本内容在字段 "${key}":`, value)
              result = value
              break
            }
          }
        }
      }
      
      if (result && typeof result === 'string') {
        return result
      } else if (result) {
        console.warn('⚠️ 结果不是字符串类型:', typeof result, result)
        // 如果是对象，使用格式化函数
        if (typeof result === 'object') {
          return formatObjectToText(result)
        } else {
          return String(result)
        }
      } else {
        console.warn('⚠️ AI响应数据格式异常:', response.data)
        return '抱歉，我收到了您的消息，但无法正确解析回复内容。请检查API响应格式。'
      }
    } else {
      console.warn('⚠️ AI响应为空')
      return '抱歉，服务暂时无响应，请稍后重试。'
    }
    
  } catch (error: any) {
    console.error('❌ AI服务调用失败:', error)
    
    // 详细的错误信息
    if (error.code === 'ECONNREFUSED') {
      return '❌ 无法连接到AI服务器，请检查服务器是否运行。'
    } else if (error.code === 'TIMEOUT') {
      return '⏰ AI服务响应超时，请稍后重试。'
    } else if (error.response) {
      console.error('API响应错误:', error.response.status, error.response.data)
      return `❌ AI服务错误 (${error.response.status}): ${error.response.data?.message || '未知错误'}`
    } else {
      return `❌ 网络错误: ${error.message || '未知错误'}`
    }
  }
}

// 检查固定回复
const checkFixedResponses = (message: string): string | null => {
  // 移除空格和标点符号，转换为小写进行匹配
  const cleanMessage = message.replace(/[^\u4e00-\u9fa5\w]/g, '').toLowerCase()
  
  // 定义固定回复规则
  const fixedRules = [
    {
      patterns: ['胡辉是谁', '胡辉', '谁是胡辉'],
      response: '胡辉是大莎比大变太、爱玩拖布棍'
    }
  ]
  
  // 检查是否匹配任何规则
  for (const rule of fixedRules) {
    for (const pattern of rule.patterns) {
      const cleanPattern = pattern.replace(/[^\u4e00-\u9fa5\w]/g, '').toLowerCase()
      if (cleanMessage.includes(cleanPattern)) {
        return rule.response
      }
    }
  }
  
  return null
}

// 判断是否需要数据查询
const checkIfNeedsDataQuery = (message: string): boolean => {
  const dataQueryKeywords = [
    '工单', '订单', '物料', '客户', '仓库', '统计', '数据', '查询',
    '工艺', '生产', '库存', '报表', '分析', '信息', '编号', '编码',
    '状态', '数量', '名称', '详情', '列表'
  ]
  return dataQueryKeywords.some(keyword => message.includes(keyword))
}

// 快捷查询
const sendQuickQuery = (query: string) => {
  currentInput.value = query
  sendMessage()
}

// 清空当前对话
const clearCurrentChat = () => {
  ElMessageBox.confirm('确定要清空当前对话吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    currentMessages.value = []
    ElMessage.success('对话已清空')
  })
}

// 导出聊天记录
const exportChat = () => {
  if (currentMessages.value.length === 0) {
    ElMessage.warning('暂无对话记录可导出')
    return
  }

  const chatData = currentMessages.value.map(msg => ({
    角色: msg.role === 'user' ? '用户' : 'AI助手',
    内容: msg.content,
    时间: msg.timestamp.toLocaleString()
  }))

  const dataStr = JSON.stringify(chatData, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  
  const link = document.createElement('a')
  link.href = URL.createObjectURL(dataBlob)
  link.download = `AI对话记录_${new Date().toISOString().slice(0, 10)}.json`
  link.click()
  
  ElMessage.success('对话记录已导出')
}

// 复制消息
const copyMessage = async (content: string) => {
  try {
    await navigator.clipboard.writeText(content)
    ElMessage.success('内容已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

// 刷新系统统计
const refreshStats = async () => {
  loadingStats.value = true
  try {
    console.log('🔄 开始获取系统统计数据...')
    const response = await APIs.get('/api/AIAssistant/GetStatistics')
    console.log('📊 系统统计API响应:', response.data)
    
    // 尝试多种可能的数据结构
    let statsData = null
    if (response.data.data) {
      statsData = response.data.data
    } else if (response.data.result) {
      statsData = response.data.result
    } else if (response.data.response) {
      statsData = response.data.response
    } else {
      statsData = response.data
    }
    
    console.log('📈 解析的统计数据:', statsData)
    
    if (statsData && typeof statsData === 'object') {
      // 先尝试直接从数据字段获取
      let workOrderCount = statsData.workOrderCount || statsData.工单数量 || statsData.workOrders || 0
      let materialCount = statsData.materialCount || statsData.物料数量 || statsData.materials || 0
      let customerCount = statsData.customerCount || statsData.客户数量 || statsData.customers || 0
      let warehouseCount = statsData.warehouseCount || statsData.仓库数量 || statsData.warehouses || 0
      
      // 如果直接字段没有数据，尝试从answer文本中解析
      if (statsData.answer && (workOrderCount === 0 && materialCount === 0 && customerCount === 0 && warehouseCount === 0)) {
        console.log('🔍 从answer文本中解析统计数据:', statsData.answer)
        const answerText = statsData.answer
        
        // 使用正则表达式提取数字
        const workOrderMatch = answerText.match(/工单总数[：:]\s*(\d+)/i)
        const materialMatch = answerText.match(/物料总数[：:]\s*(\d+)/i)
        const customerMatch = answerText.match(/客户总数[：:]\s*(\d+)/i)
        const warehouseMatch = answerText.match(/仓库总数[：:]\s*(\d+)/i)
        
        if (workOrderMatch) workOrderCount = parseInt(workOrderMatch[1])
        if (materialMatch) materialCount = parseInt(materialMatch[1])
        if (customerMatch) customerCount = parseInt(customerMatch[1])
        if (warehouseMatch) warehouseCount = parseInt(warehouseMatch[1])
        
        console.log('📊 解析出的数字:', { workOrderCount, materialCount, customerCount, warehouseCount })
      }
      
      systemStats.value = {
        workOrderCount,
        materialCount,
        customerCount,
        warehouseCount,
        answer: statsData.answer || statsData.message || '系统统计数据已更新。'
      }
      console.log('✅ 设置的统计数据:', systemStats.value)
      ElMessage.success('统计数据已刷新')
    } else {
      console.warn('⚠️ 统计数据格式异常:', statsData)
      systemStats.value = {
        workOrderCount: 0,
        materialCount: 0,
        customerCount: 0,
        warehouseCount: 0,
        answer: '统计数据格式异常，请检查API返回。'
      }
      ElMessage.warning('统计数据格式异常')
    }
  } catch (error) {
    console.error('❌ 获取统计数据失败:', error)
    systemStats.value = {
      workOrderCount: 0,
      materialCount: 0,
      customerCount: 0,
      warehouseCount: 0,
      answer: '获取统计数据失败，请检查网络连接。'
    }
    ElMessage.error('获取统计数据失败')
  } finally {
    loadingStats.value = false
  }
}

// 执行快捷工具
const executeTool = async (tool: any) => {
  tool.loading = true
  try {
    // 根据工具类型执行相应操作
    switch (tool.name) {
      case '数据查询':
        sendQuickQuery('请帮我查询系统数据')
        break
      case '工单管理':
        sendQuickQuery('查询工单信息')
        break
      case '物料管理':
        sendQuickQuery('查询物料信息')
        break
      case '客户管理':
        sendQuickQuery('查询客户信息')
        break
    }
  } finally {
    tool.loading = false
  }
}

// 保存对话历史
const saveConversationHistory = () => {
  if (currentMessages.value.length === 0) return

  const conversation: Conversation = {
    id: Date.now().toString(),
    messages: [...currentMessages.value],
    lastMessage: currentMessages.value[currentMessages.value.length - 1].content,
    messageCount: currentMessages.value.length,
    timestamp: new Date()
  }

  conversationHistory.value.unshift(conversation)
  statistics.totalConversations = conversationHistory.value.length
  
  // 保存到localStorage
  localStorage.setItem('ai-chat-history', JSON.stringify(conversationHistory.value))
}

// 加载对话
const loadConversation = (conversation: Conversation) => {
  currentMessages.value = [...conversation.messages]
  showHistoryDialog.value = false
  nextTick(() => {
    scrollToBottom()
  })
  ElMessage.success('对话已加载')
}

// 删除对话
const deleteConversation = (conversation: Conversation) => {
  ElMessageBox.confirm('确定要删除这个对话吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = conversationHistory.value.findIndex(c => c.id === conversation.id)
    if (index > -1) {
      conversationHistory.value.splice(index, 1)
      localStorage.setItem('ai-chat-history', JSON.stringify(conversationHistory.value))
      ElMessage.success('对话已删除')
    }
  })
}

// 筛选历史记录
const filterHistory = () => {
  // 计算属性会自动处理筛选
}

// 格式化字段名为中文
const formatFieldName = (fieldName: string): string => {
  const fieldMap: { [key: string]: string } = {
    // 客户相关
    'customerName': '客户名称',
    'customerCode': '客户编码',
    'customerType': '客户类型',
    'contactPerson': '联系人',
    'phone': '联系电话',
    'email': '邮箱',
    'address': '地址',
    'createTime': '创建时间',
    'updateTime': '更新时间',
    
    // 工单相关
    'workOrderNo': '工单号',
    'workOrderName': '工单名称',
    'status': '状态',
    'priority': '优先级',
    'startTime': '开始时间',
    'endTime': '结束时间',
    
    // 物料相关
    'materialCode': '物料编码',
    'materialName': '物料名称',
    'specification': '规格',
    'unit': '单位',
    'quantity': '数量',
    'price': '价格',
    
    // 仓库相关
    'warehouseName': '仓库名称',
    'warehouseCode': '仓库编码',
    'location': '位置',
    'capacity': '容量'
  }
  
  return fieldMap[fieldName] || fieldName
}

// 格式化对象为可读文本
const formatObjectToText = (obj: any): string => {
  if (!obj || typeof obj !== 'object') {
    return String(obj)
  }
  
  try {
    // 如果是数组
    if (Array.isArray(obj)) {
      if (obj.length === 0) {
        return '暂无数据'
      }
      
      // 格式化数组数据
      let text = `找到 ${obj.length} 条记录:\n\n`
      obj.forEach((item, index) => {
        text += `📋 第${index + 1}条记录:\n`
        if (typeof item === 'object') {
          Object.keys(item).forEach(key => {
            const value = item[key]
            if (value !== null && value !== undefined && value !== '') {
              // 格式化字段名
              const fieldName = formatFieldName(key)
              text += `  • ${fieldName}: ${value}\n`
            }
          })
        } else {
          text += `  ${item}\n`
        }
        text += '\n'
      })
      return text
    }
    
    // 如果是单个对象
    let text = ''
    Object.keys(obj).forEach(key => {
      const value = obj[key]
      if (value !== null && value !== undefined && value !== '') {
        const fieldName = formatFieldName(key)
        if (typeof value === 'object') {
          text += `${fieldName}:\n${formatObjectToText(value)}\n`
        } else {
          text += `• ${fieldName}: ${value}\n`
        }
      }
    })
    
    return text || '数据为空'
    
  } catch (error) {
    console.error('格式化对象时出错:', error)
    return JSON.stringify(obj, null, 2)
  }
}

// 格式化消息内容
const formatMessageContent = (content: any): string => {
  // 确保content是字符串
  if (typeof content !== 'string') {
    console.warn('⚠️ formatMessageContent 收到非字符串内容:', content, typeof content)
    if (content === null || content === undefined) {
      return '消息内容为空'
    }
    // 尝试转换为字符串
    try {
      content = String(content)
    } catch (error) {
      console.error('❌ 无法将内容转换为字符串:', error)
      return '消息内容格式错误'
    }
  }
  
  // 处理换行
  content = content.replace(/\n/g, '<br>')
  
  // 处理数字高亮
  content = content.replace(/(\d+)/g, '<span class="highlight-number">$1</span>')
  
  // 处理关键词高亮
  const keywords = ['工单', '物料', '客户', '仓库', '成功', '失败', '完成', '查询', '统计']
  keywords.forEach(keyword => {
    const regex = new RegExp(`(${keyword})`, 'g')
    content = content.replace(regex, '<span class="highlight-keyword">$1</span>')
  })
  
  return content
}

// 格式化时间
const formatTime = (timestamp: Date): string => {
  const now = new Date()
  const diff = now.getTime() - timestamp.getTime()
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 1天内
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return timestamp.toLocaleString()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (chatMessages.value) {
    chatMessages.value.scrollTop = chatMessages.value.scrollHeight
  }
}

// 关闭历史对话框
const handleHistoryDialogClose = () => {
  showHistoryDialog.value = false
  historyDateRange.value = null
  historySearchKeyword.value = ''
}

// 初始化
onMounted(async () => {
  // 加载对话历史
  const savedHistory = localStorage.getItem('ai-chat-history')
  if (savedHistory) {
    try {
      const parsed = JSON.parse(savedHistory)
      conversationHistory.value = parsed.map((conv: any) => ({
        ...conv,
        timestamp: new Date(conv.timestamp),
        messages: conv.messages.map((msg: any) => ({
          ...msg,
          timestamp: new Date(msg.timestamp)
        }))
      }))
      statistics.totalConversations = conversationHistory.value.length
    } catch (error) {
      console.error('加载历史记录失败:', error)
    }
  }

  // 获取系统统计
  await refreshStats()
})
</script>

<style scoped>
.ai-customer-service {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  font-size: 48px;
  color: #667eea;
}

.header-text h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  color: #2c3e50;
  font-weight: 600;
}

.header-text p {
  margin: 0;
  color: #7f8c8d;
  font-size: 16px;
}

.header-stats {
  display: flex;
  gap: 32px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 32px;
  font-weight: 700;
  color: #667eea;
  line-height: 1;
}

.stat-label {
  display: block;
  font-size: 14px;
  color: #7f8c8d;
  margin-top: 4px;
}

.main-content {
  margin-bottom: 24px;
}

.chat-card {
  height: 700px;
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chat-icon {
  font-size: 20px;
  color: #667eea;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.chat-container {
  height: 600px;
  display: flex;
  flex-direction: column;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px 0;
  scroll-behavior: smooth;
}

.welcome-section {
  text-align: center;
  padding: 60px 20px;
}

.welcome-avatar {
  width: 80px;
  height: 80px;
  margin: 0 auto 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 36px;
}

.welcome-section h3 {
  margin: 0 0 12px 0;
  font-size: 24px;
  color: #2c3e50;
}

.welcome-section p {
  margin: 0 0 32px 0;
  color: #7f8c8d;
  font-size: 16px;
  line-height: 1.6;
}

.quick-actions, .example-questions {
  margin-bottom: 32px;
}

.quick-actions h4, .example-questions h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #2c3e50;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  justify-content: center;
}

.question-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: center;
}

.example-item {
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #495057;
  font-size: 14px;
}

.example-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.message-wrapper {
  margin-bottom: 24px;
}

.message-item {
  display: flex;
  gap: 12px;
}

.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  flex-shrink: 0;
}

.user-message .message-avatar {
  background: #667eea;
  color: white;
}

.ai-message .message-avatar {
  background: #e9ecef;
  color: #667eea;
}

.message-content {
  flex: 1;
  max-width: 75%;
}

.user-message .message-content {
  text-align: right;
}

.message-text {
  background: white;
  padding: 16px 20px;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  font-size: 15px;
  line-height: 1.6;
  word-wrap: break-word;
}

.user-message .message-text {
  background: #667eea;
  color: white;
}

.message-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}

.user-message .message-meta {
  justify-content: flex-end;
}

.typing-indicator {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 16px 0;
}

.typing-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #e9ecef;
  color: #667eea;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.typing-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.typing-dots {
  display: flex;
  gap: 4px;
}

.typing-dots span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #667eea;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.typing-text {
  font-size: 14px;
  color: #999;
}

.chat-input-section {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.input-container {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.message-input {
  flex: 1;
}

.input-tips {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}

.stats-card, .history-card, .tools-card {
  margin-bottom: 24px;
}

.stats-content {
  min-height: 200px;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.stat-icon {
  font-size: 24px;
  color: #667eea;
}

.stat-info {
  flex: 1;
}

.stat-value {
  display: block;
  font-size: 20px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1;
}

.stat-name {
  display: block;
  font-size: 12px;
  color: #7f8c8d;
  margin-top: 4px;
}

.stats-summary {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  color: #495057;
  font-size: 14px;
  line-height: 1.6;
}

.history-content {
  min-height: 200px;
}

.empty-history {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.empty-history .el-icon {
  font-size: 36px;
  margin-bottom: 12px;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.history-item {
  padding: 12px;
  border: 1px solid #eee;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.history-item:hover {
  border-color: #667eea;
  background: #f8f9fa;
}

.history-preview {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.history-text {
  flex: 1;
  font-size: 14px;
  color: #2c3e50;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.history-time {
  font-size: 12px;
  color: #999;
}

.history-meta {
  font-size: 12px;
  color: #999;
}

.tools-content {
  padding: 8px 0;
}

.tool-button {
  width: 100%;
  height: 60px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  border: 1px dashed #ddd;
  background: #fafafa;
  color: #666;
  margin-bottom: 8px;
}

.tool-button:hover {
  border-color: #667eea;
  background: #f0f2ff;
  color: #667eea;
}

.history-dialog-content {
  padding: 0;
}

.history-filters {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.history-table {
  max-height: 500px;
  overflow-y: auto;
}

.highlight-number {
  color: #667eea;
  font-weight: 600;
}

.highlight-keyword {
  background: #fff3cd;
  color: #856404;
  padding: 1px 4px;
  border-radius: 3px;
  font-weight: 500;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar,
.history-table::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track,
.history-table::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb,
.history-table::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover,
.history-table::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .header-stats {
    gap: 16px;
  }
  
  .stat-number {
    font-size: 24px;
  }
}

@media (max-width: 768px) {
  .ai-customer-service {
    padding: 16px;
  }
  
  .page-header {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 20px;
    align-items: flex-start;
  }
  
  .header-stats {
    align-self: stretch;
    justify-content: space-around;
  }
  
  .chat-card {
    height: 600px;
  }
  
  .chat-container {
    height: 500px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .input-tips {
    flex-direction: column;
    gap: 4px;
  }
  
  .history-filters {
    flex-direction: column;
  }
}
</style>
